package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    /**
     * 查询所有地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        return addressMapper.list(BaseContext.getCurrentId());
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook one() {
        return addressMapper.one(BaseContext.getCurrentId());
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void insert(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressMapper.insert(addressBook);
    }

    /**
     * 根据id 查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressMapper.getById(id);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressMapper.deleteById(id);
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressMapper.update(addressBook);
    }

    /**
     * 根据id修改默认地址
     * @param id
     */
    @Override
    public void updateById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .isDefault(1)
                .build();
        List<AddressBook> list = addressMapper.list(BaseContext.getCurrentId());
        list.forEach(i->{
            i.setIsDefault(0);
            addressMapper.update(i);
        });
        addressMapper.update(addressBook);
    }
}
